import router from './router'
import store from './store'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  const url = to.path
  const whiteList = ['/login', '/404']
  // 已登录，还去登录页就跳到首页
  if (token && url === '/login') {
    next('/')
  }
  // 已登录不跳到首页直接放行
  if (token && url !== '/login') {
    next()
  }
  //
  if (token && !store.state.user.userInfo.id) {
    await store.dispatch('user/getuserinfo')
    const routes = await store.dispatch('permission/filterRoutes', store.state.user.userPerm.menus)
    router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
    // 解决浏览器刷新空白问题
    next(to.path)
  }
  // 未登录，不在白名单，跳到登录页
  if (!token && !whiteList.includes(url)) {
    next('/login')
  }
  //   未登录，在白名单，放行
  if (!token && whiteList.includes(url)) {
    next()
  }
})

